$(document).ready(function() {
    var admin_url = $('#base_url').val()
    // display filter item with cooke displsy
    var filteritemslide = getCookie('filteritemslide');

    if (filteritemslide == 'plus') {
        $('#clospe-item-filter').hide();
        $('#icon-item-filter').removeClass();
        $('#icon-item-filter').addClass('icon-minus');
    } else if (filteritemslide == 'minus') {
        $('#clospe-item-filter').show();
        $('#icon-item-filter').removeClass();
        $('#icon-item-filter').addClass('icon-plus');
    }

    $('#icon-item-filter').bind('click', function() {
        $('#clospe-item-filter').slideToggle('slow', function() {




            if ($('#clospe-item-filter').is(':hidden') == true) {
                setCookie('filteritemslide', 'plus', 1);
                $('#icon-item-filter').removeClass();
                $('#icon-item-filter').addClass('icon-minus');

            } else {
                setCookie('filteritemslide', 'minus', 1);
                $('#icon-item-filter').removeClass();
                $('#icon-item-filter').addClass('icon-plus');
            }

        });

    });



    /*===== craete cooke =======*/
    function setCookie(c_name, value, exdays)
    {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }



    function getCookie(c_name)
    {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++)
        {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name)
            {
                return unescape(y);
            }
        }
    }

    /*===== craete cooke =======*/



    /*===== Admin action Model Display =======
     * 
     * 
     *===== Admin action Model Display =======*/

    // display mearg order


    /**
     * 
     * @param {type} mearg_input
     * @param {type} divtoload
     * @returns {undefined}
     */
    function display_file_action(mearg_input, divtoload) {




        if (divtoload == '') {
            divtoload = '#action_load_mudle';
        }

        $('' + mearg_input + '').bind('change', function() {



            $.ajax({
                url: admin_url + '/ajax/load_thems_helper',
                type: 'POST',
                data: {
                    file: $(this).val()
                },
                error: function() {
                    alert('Ajax Load Error');
                },
                beforeSend: function() {
                    $('' + divtoload + '').addClass('ajaxload');
                },
                success: function(data) {
                    $('' + divtoload + '').html(data);
                    $('' + divtoload + '').removeClass('ajaxload');
                }
            });


        });
    }



    // load mearge file
    display_file_action('.droop_tool_box', '');


    // load statues file

    display_file_action('.droop_tool_box_statues', '');


    // confirm delete

    $('.delete_confirm').bind('click', function() {
        if (confirm('{Sure you want to make the deletion process}') == false) {
            return false;
        } else {
            return true;
        }
    });

    $('#checkall').bind('click', function() {
        if ($(this).is(':checked') == true) {
            $('.checkall').attr('checked', 'checked');
        } else {
            $('.checkall').removeAttr('checked');
        }

    });
    /*===== Admin action Model Display =======
     * 
     * 
     *===== Admin action Model Display =======*/
    var dateformat='yy-mm-dd';
    $( "#drop_date,.drop_date" ).attr('autocomplete','off');
    $( "#drop_date,.drop_date" ).datepicker({
        dateFormat: dateformat
    });
    //======= users auto commplite //	
    $("input#usernameauto").autocomplete({
        source: function( request, response ) {
                  
            $.ajax({
                url: admin_url+"/ajax/user_autocomplite",
                type: "post",
                dataType: "json",
                data: {
                    term: request.term
                },
                success: function(data) {
                    response(data);
                }
            });
        },
        minLength: 1, //search after two characters
        select: function(event,ui){
		    
        }
    });
        
        
    //======= users auto commplite //	
    $("#email_autocomplite").autocomplete({
        source: function( request, response ) {
                  
            $.ajax({
                url: admin_url+"/ajax/email_autocomplite",
                type: "post",
                dataType: "json",
                data: {
                    term: request.term
                },
                success: function(data) {
                    response(data);
                }
            });
        },
        minLength: 1, //search after two characters
        select: function(event,ui){
		    
        }
    });
 
            
    // length sms message
    $('#sms_message').keyup(function(){
        //get the limit from maxlength attribute
        var limit = $(this).attr('maxlength');
        $('#maxlength').html(limit);
      
        //get the current text inside the textarea
        var text = $(this).val();
        //count the number of characters in the text
        var chars = text.length;

        //check if there are more characters then allowed
        if(chars > limit){
            //and if there are use substr to get the text before the limit
            var new_text = text.substr(0, limit);

            //and change the current text with the new text
            $(this).val(new_text);
        }else{
            $('#maxlength').text(limit-chars);
        }
    });

    ///===================== alert admin ==================//
    setInterval(function() {
        // Do something After 5 min
     

        $.getJSON(admin_url+'/ajax/admin_alert', function(data) {
            var items = '';
            // old count ;
            var old_count=$('#admin_alert').text(); 
  
            $.each(data, function(key, val) {
                if(key !='all_count'){
                    items +='<li class="li_adminalert"><div class="btn btn-danger li_adminalert_count">' + val.count + '</div><a  class="btn li_adminalert_a" href="' +admin_url+'/'+val.url + '">' +val.message + '</a></li>'; 
          
                }else{
                    $('#admin_alert').text(val); 
                    // Display new count in page title
                    if(val > old_count){
                        document.title = " لديك  "+(val-old_count)+" تحديث جديد";   
                    }
                }
   
            });
            var display_alert='<ul class="black-box-dropdown" > '+items+' </ul>';
            $('#admin_alert_box').html(display_alert);

        });

    }, 300000);


    //================= Edit ===============//
    $('.weight_eidt span').each(function(index){
       
 
        $(this).bind('click',function(){
            // Display input and hidden value  
            $(this).fadeOut('fast',function(){
                var input=$('.weight_eidt:eq('+index+')').children('input');
                var span=$(this);
                input.fadeIn('fast');
            
            
                input.bind('focusout',function(){
                    // Update Data  input and hidden value  
                    $(this).fadeOut('fast',function(){
                        // send and update ajax
                        var weight_value=$(this).val();
                        var item_id=$('.weight_eidt:eq('+index+')').attr('id');
                        $.ajax({
                            url  : admin_url+'/ajax/weight_update',
                            type : "post",
                            data : {
                                weight: weight_value,
                                id:item_id
                            },
                            error: function(){
                                alert('Ajax Error');
                                span.removeClass('ajaxload');
                            },
                            success:function(data){
                                span.text(data);
                                span.removeClass('ajaxload');
                            
                            },
                            beforeSend:function(){
                                span.addClass('ajaxload');
                              
                            }
                        });
                      
                      
                        // show value span
                        span.fadeIn();
                    });
                   
                });
            });
        
        });
  
    });

    //================= Edit ===============//
    $('.tip').tooltip({
        html:true
    });


    // =================== add box ===============//
    $('#add_box_item').bind('click',function(){
        var file= $('#site_url').val()+'/application/views/admin/helper/action/add_box.php';
 
        $.get(file, function(data) {
            $('.box_item_incress').delay(1000).before(data);
 
        });
   
        return false;
    });


    $('#addinbox_main').bind('click', function(){
        var error='';
        $('.addboxitemform .input input').each(function(index){
            var input_value=$(this).val();
     
            if(input_value ==''){
                $(this).addClass('error');
                error=1;
            }else{
                $(this).removeClass('error');
            }
     
        });

        if(error == ''){
            return true; 
        }else{
       
            return false; 
        }
   
    });
    //================== valid input add box =================//


    //============== edit in the same page =================//

    var element_each   = $('.shipping_rate_cost');
    var element_total  = '.shipping_rate_total';
    var element_lbs    = '.shipping_rate_lbs';

    element_each.each(function(index){
       
        /**
         * 
        /// ======================== statrt  lbs =================///

       
        $(this).children(element_lbs).children('span').bind('click',function(){
            
            var lbs_span=$(this);
            var lbs_input=$(this).parent().children('input');
            var id= $(this).attr('id');
        
            lbs_span.fadeOut('fast',function(){
                lbs_input.fadeIn('slow');
            });

        });
        // lbs
        $(this).children(element_lbs).children('input').bind('focusout',function(){
            var lbs_span=$(this).parent().children('span');
            $(this).fadeOut('fast', function(){
                lbs_span.fadeIn('slow');
            // send ajax
                    
            });
               
        });   
            
        /// ======================== end lbs =================///
  
   */
 
        /// ======================== statrt  Total =================///
        $(this).children(element_total).children('span').bind('click',function(){
            
            var lbs_span=$(this);
            var lbs_input=$(this).parent().children('input');
            var id= $(this).attr('id');
        
            lbs_span.fadeOut('fast',function(){
                lbs_input.fadeIn('slow');
            });

        });
        // Total
        $(this).children(element_total).children('input').bind('focusout',function(){
            var lbs_spans=$(this).parent(element_total).children('span');
               var rate_value=$(this).val();
                var rate_id=$(this).attr('id');
            $(this).fadeOut('fast', function(){
                lbs_spans.fadeIn('slow');
                // send ajax 

                $.ajax({
                    url  : admin_url+'/ajax/rate_update',
                    type : "post",
                    data : {
                        total : rate_value,
                        id    : rate_id
                    },
                    error: function(){
                        alert('Ajax Error');
                        lbs_spans.removeClass('ajaxload');
                    },
                    success:function(data){
                        lbs_spans.text(data);
                        lbs_spans.removeClass('ajaxload');
                            
                    },
                    beforeSend:function(){
                        lbs_spans.addClass('ajaxload');
                              
                    }
                });
            
            
            });
               
        });   
            
    /// ======================== end Total =================///
    });




});